<template>
<div class="container">
    <div class="topimg">识别种类统计</div>
    <div class="chart" id="chart">

    </div>
</div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
import { fishWeightApi } from "@/api/fishWeight";

onMounted(() => { 
var chartDom = document.getElementById('chart');
var myChart = echarts.init(chartDom);
var option;

fishWeightApi.getLatestRecord().then(res => {
  // 处理数据统计
  const statistics: { [key: string]: number } = {};
  res.data.forEach((item: any) => {
    const fishType = item.recognitionResult || '未识别成功';
    statistics[fishType] = (statistics[fishType] || 0) + 1;
  });

  // 转换为图表需要的格式并限制只显示前5个
  const chartData = Object.entries(statistics)
    .map(([type, count]) => [type, count])
    .sort((a, b) => (b[1] as number) - (a[1] as number)) // 按数量降序排序
    .slice(0, 5); // 只取前5个数据

option = {
  dataset: [
    {
      dimensions: ['种类', '数量'],
      source: chartData
    },
    {
      transform: {
        type: 'sort',
        config: { dimension: '数量', order: 'desc' } 
      }
    }
  ],
  xAxis: {
    type: 'category',
    axisLabel: { 
      interval: 0, 
      color: 'whitesmoke',
      fontSize: 18
    }
  },
  yAxis: {
    // 修改y轴字体大小和颜色
    axisLabel: {
      color: 'whitesmoke',
      fontSize: 18
    }
  },
  series: {
    type: 'bar',
    encode: { x: '种类', y: '数量' },
    datasetIndex: 1 // 修改为使用排序后的数据集
  }
};

option && myChart.setOption(option);
});
});
</script>

<style scoped>
.container{
    width: 100%;
    height: 100%;
    /* background-color: rgba(0, 0, 0, 0.1); */
    border-radius: 10px;
}
.topimg{
  font-size: 24px;
  height: 40px;
  background-image: url(@/assets/top.png);
  background-size: cover;
  text-align: center;
}
.chart{
    width: 100%;
    height: 90%;
    /* background-color: white; */
    border-radius: 10px;
    background-color: rgba(0, 0, 0, 0.1);

}
</style>